package com.shixun.milktea.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.net.Authenticator;

/**
 * @author Zourongsheng
 * @version 1.0
 * @date 2022/6/9 20:00
 */
@Component
public class RedisUtil {
    @Autowired
    private RedisTemplate<String,String> strRedisTemplate;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    /**
     * 缓存token
      * @param key
     * @param token
     */
    public void save(String key,String token){
        key +="_token";
        strRedisTemplate.opsForValue().set(key, token);
    }

    /**
     * 缓存用户身份
     * @param key
     * @param authentication
     */
    public void save(String key, Authentication authentication){
        redisTemplate.opsForValue().set(key,authentication);
    }

    /**
     * 从缓存中获取token
     * @param key
     * @return
     */
    public String getToken(String key){
        key +="_token";
        return strRedisTemplate.opsForValue().get(key);
    }

    /**
     * 从缓存中获取用户身份
     * @param key
     * @return
     */
    public Authentication getAuthentication(String key){
        return (Authentication) redisTemplate.opsForValue().get(key);
    }

    /**
     * 清除缓存
     * @param key
     */
    public void delete(String key){
        redisTemplate.delete(key);
        strRedisTemplate.delete(key);
    }
}
